package com.personal.service.Impl;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.personal.service.EmailService;
import com.personal.service.dto.EmailDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EmailServiceImpl implements EmailService {

    @Value("${spring.mail.email}")
    private String email;

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.port}")
    private String port;

    @Override
    public void send(EmailDto emailDto) {

        if (host == null || username == null || password == null){
            throw new RuntimeException("配置邮件异常");
        }

        //设置
        MailAccount account = new MailAccount();
        //端口
        account.setPort(Integer.parseInt(port));
        //发送人
        account.setFrom(username + "<" + email + ">");
        //主机
        account.setHost(host);
        //发送人名称
        account.setUser(username);
        //授权码
        account.setPass(password);
        account.setAuth(true);
        //ssl方式发送
        account.setSslEnable(true);
        //使用安全连接
        account.setStarttlsEnable(true);

        try {
            int size = emailDto.getTos().size();
            Mail.create(account)
                    .setTos(emailDto.getTos().toArray(new String[size]))
                    .setTitle(emailDto.getSubject())
                    .setContent(emailDto.getContent())
                    .setHtml(true)
                    .setUseGlobalSession(false)
                    .send();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
